package com.jt.service.impl;

import com.jt.exception.MyRunException;
import com.jt.service.FileService;
import com.jt.vo.ImageVo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.xml.crypto.Data;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.logging.SimpleFormatter;

@Service
public class FileServiceImpl implements FileService {
    private String fileLocalDir="D:/img";
    private static Set<String> typeSet=new HashSet<>();
    static {
        typeSet.add(".jpg");
        typeSet.add(".png");
        typeSet.add(".gif");
    }

    @Override
    public ImageVo upload(MultipartFile multipartFile) {
        String fileName=multipartFile.getOriginalFilename();
        fileName=fileName.toLowerCase();
        int index=fileName.lastIndexOf(".");
        String TypeName=fileName.substring(index);
        if(!typeSet.contains(TypeName))return ImageVo.fail();

        try {
            BufferedImage bufferedImage= ImageIO.read(multipartFile.getInputStream());
            int width=bufferedImage.getWidth();
            int height=bufferedImage.getHeight();
            if(width==0||height==0)return ImageVo.fail();

            String dateDir=new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String finalDir=fileLocalDir+dateDir;
            File file=new File(finalDir);
            if(!file.exists())file.mkdirs();

            String UUID= java.util.UUID.randomUUID().toString().replace("-","");
            File file1=new File(finalDir+UUID+TypeName);
            multipartFile.transferTo(file1);
            return ImageVo.success(null,width,height);


        } catch (IOException e) {
            e.printStackTrace();
            return ImageVo.fail();
        }





    }
}
